package com.qfedu.common.sms.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;

/**
 * 发送短信工具类（修正版）
 */
public class AliSmsUtils {
    private static IAcsClient client;
    // 建议从环境变量或配置文件读取，避免硬编码
    private static final String ACCESS_KEY_ID = "LTAI5tSKAkFGYBFvPL4igez1";
    private static final String ACCESS_KEY_SECRET = "3XKwGZF8A69xLsu75DXzTf3F6jPkMf";

    static {
        // 关键修正：RegionId 必须为 cn-hangzhou
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        client = new DefaultAcsClient(profile);
    }

    /**
     * 发送短信
     *
     * @param signName     短信签名（需已审核）
     * @param templateCode 模板ID（测试模板需4-6位数字参数）
     * @param phone        手机号（测试需为备案号码）
     * @param code         验证码（测试模板需4-6位纯数字）
     */
    public static void sendSms(String signName, String templateCode, String phone, String code) {
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setPhoneNumbers(phone);
        // 确保参数符合模板要求（测试模板：4-6位纯数字）
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("错误码: " + e.getErrCode());
            System.out.println("错误信息: " + e.getErrMsg());
            System.out.println("请求ID: " + e.getRequestId());
        }
    }
}
